﻿using AutoStockTrade.Model;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Serialization;

namespace AutoStockTrade
{
    public static class Util
    {
        public static bool IsEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        /// <summary>
        /// List扩展方法，判断List是否为空
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool IsEmpty<T>(this List<T> list)
        {
            return list == null || list.Count == 0 ? true : false;
        }

        /// <summary>
        /// List扩展方法，判断List是否为空
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool IsEmpty(this Array list)
        {
            return list == null || list.Length == 0 ? true : false;
        }

        public static void Wait()
        {
            Thread.Sleep(500);
        }

        public static void XMLSerializer<T>(string filePath, T t) where T : ModelBase
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                using (Stream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    xs.Serialize(stream, t);
                }
            }
            catch
            {
                throw;
            }
        }
    }

    public sealed class CacheSingleton : IDisposable
    {
        private IUnityContainer container = null;
        private static readonly CacheSingleton instance = new CacheSingleton();

        private CacheSingleton() { }

        public static CacheSingleton Instance
        {
            get
            {
                return instance;
            }
        }

        public IUnityContainer GetUnityContainer()
        {
            if (container == null)
            {
                container = new UnityContainer();
            }
            return container;
        }

        public void Register<T>(T pInstance)
        {
            IUnityContainer unityContainer = GetUnityContainer();
            unityContainer.RegisterInstance<T>(pInstance);
        }

        public void Dispose()
        {
            if (container != null)
            {
                container.Dispose();
            }
        }
    }
}
